package com.sure.supermarketserver.security.home.impl;

import com.sure.supermarketserver.common.CurrentUser;
import com.sure.supermarketserver.common.Utils;
import com.sure.supermarketserver.security.home.HomeService;
import com.sure.supermarketserver.security.home.MenuVO;
import com.sure.supermarketserver.security.home.dao.HomeDao;
import com.sure.supermarketserver.security.home.Module;
import com.sure.supermarketserver.security.home.HomeDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class HomeServiceImpl implements HomeService {

    @Resource
    private HomeDao homeDao;
    @Override
    public List<MenuVO> getMenus(CurrentUser currentUser) {

        List<Module> list = homeDao.findModuleByUser(currentUser.getUserId());

        List<MenuVO> menuList = new ArrayList<>();
        MenuVO menu = null;

        for(Module module:list){
            if(menu == null || !menu.getId().equals(module.getP_id())){
                menu = new MenuVO();
                menu.setId(module.getP_id());
                menu.setName(module.getP_name());
                menu.setChildren(new ArrayList<MenuVO>());

                menuList.add(menu);
            }

            MenuVO child = new MenuVO();
            child.setId(module.getM_id());
            child.setName(module.getM_name());
            child.setUrl(module.getMo_web_route());

            menu.getChildren().add(child);

        }
        return menuList;
    }

    @Override
    public void setAvatar(CurrentUser currentUser, String filename) {
        homeDao.updateAvatar(currentUser.getUserId(), filename);
    }

    //查询
    @Override
    public Map<String, Object> getHomeList(HomeDto dto) {
        return Utils.getPage(dto, ()-> homeDao.findHomeList(dto));
    }

    //增加
    @Override
    public void addHome(HomeDto dto) {
        homeDao.insertHome(dto);
    }

    //修改
    @Override
    public void updateHome(HomeDto dto) {
        homeDao.updateHome(dto);

    }

    //删除
    @Override
    public void deleteHome(Integer id) {
        homeDao.deleteHome(id);
    }
}
